package com.bose.bosecmdclient;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class CmbClient {
    private static final String LOG_TAG = "BOSECMD_CLIENT";
    private static final String BOSECMD_SERVER_ADDR = "192.168.1.1";
    private static final int BOSECMD_SERVER_PORT = 5503;
    Socket mSocket;
    String mIp = BOSECMD_SERVER_ADDR;
    int mPort = BOSECMD_SERVER_PORT;

    public Socket connect(String ip, int port) {
        if(ip == null || ip.length() <= 0 || port <= 0) return null;
        try {
            if(null == mSocket || !mIp.equals(ip) || port != mPort) {
               Log.w(LOG_TAG, "new socket connect to " + ip + ":" + port);
                mSocket = new Socket(ip, port);
                mIp = ip;
                mPort = port;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mSocket;
    }

    public static void sendData(Socket sock, byte[] cmd) {
        try {
            if(null == sock) {
                Log.w(LOG_TAG, "sendData(), socket is null ");
                return;
            }
            OutputStream outputStream = sock.getOutputStream();
            outputStream.write(cmd);
            Log.w(LOG_TAG, "Sent cmd >>> " + new String(cmd));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String receiveData(Socket sock) {
        String lines = "";
        if(null == sock) {
            Log.w(LOG_TAG, "receiveData(), socket is null ");
            return null;
        }
        try {
            InputStream inputStream = sock.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while((line = br.readLine()) != null) {
                lines = lines + line + "\n";
            }
            Log.w(LOG_TAG, "Reponse >>> " + lines);
        } catch (IOException e) {
             e.printStackTrace();
        }
        return lines;
    }

    public void disConnect() {
        try {
            if(null != mSocket) {
                mSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}